<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once(APPPATH . 'controllers/admin/admin.php');

class Projects extends Admin {

	function Projects()
	{
		parent::Admin();

		$this->load->model('projects_model');
		$this->load->model('project_members_model');
		$this->load->model('project_feeds_model');
		$this->load->model('project_urls_model');
		$this->load->model('users_model');
		
		//Get VCS types here
		//TODO: Code this when VCS libraries are installed
		//for now..
		$this->data['vcs_types'] = array(
			'no_repo' => "No Repository"
		);

		//get the list of projects
		$this->data['project_list'] = $this->projects_model->retrieve(array('deactivated' => 0));
	}

	// --------------------------------------------------------------------

	function index()
	{
		$this->data['admin_page_section'] = 'index';
		$this->layout->view('admin/projects/index', $this->data);
	}

	// --------------------------------------------------------------------

	function create()
	{
		//Get a list of all users
		$complete_user_list = $this->users_model->retrieve(array('deactivated' => 0));
		foreach($complete_user_list as $usr)
			$this->data['complete_user_list'][$usr->id] = "$usr->login ($usr->last_name, $usr->first_name)";

		if (form_was_submitted())
		{
			if ($this->_validate_create_update(TRUE))
			{
				//Create the project
				$to_add = array('name' => $this->input->post('project_name'),
					'slug' => $this->input->post('project_slug'),
					'notes' => $this->input->post('project_notes'),
					'main_url' => $this->input->post('main_url'),
					'vcs_type' => $this->input->post('vcs_type'),
					'vcs_url' => $this->input->post('vcs_url'),
					'allow_developers_to_manage_tix' => $this->input->post('allow_devs_manage_tix'),
					'allow_developers_to_enroll_users' => $this->input->post('allow_devs_manage_users'),
					'allow_proj_managers_to_manage_notes' => $this->input->post('allow_mgrs_add_notes'),
					'allow_proj_managers_to_change_settings' => $this->input->post('allow_mgrs_manage_settings'),
					'allow_proj_managers_to_enroll_users' => $this->input->post('allow_mgrs_manage_users'),
					'deactivated' => $this->input->post('deactivated'));

				$proj_id = $this->projects_model->create($to_add);

				if ($proj_id !== FALSE)
				{
					//Attempt to update the roles.. add the developers THEN the managers.
					//If anybody listed twice, they are a manager.
					$num_devs_added = $this->_set_members($this->input->post('proj_developers'), 'developer', $proj_id);
					$num_mgrs_added = $this->_set_members($this->input->post('proj_managers'), 'manager', $proj_id);

					//Then set the feeds
					$num_feeds_updated = $this->_set_feeds($proj_id);

					set_notice("Created the project {$this->input->post('project_name')} and added $num_mgrs_added managers + $num_devs_added developers.", 'good');
				}
				else
					set_notice("There was an error creating the project!", 'bad');

				
			}
			else
				set_notice("There was a problem with your submission.  See below.", 'bad');
		}

		$this->data['admin_page_section'] = 'create';
		$this->layout->view('admin/projects/index', $this->data);
	}

	// --------------------------------------------------------------------

	function update($user_slug_or_id = NULL)
	{
		$this->data['admin_page_section'] = 'update';
		$this->layout->view('admin/projects/index', $this->data);
	}

	// --------------------------------------------------------------------

	function delete($project_slug_or_id = NULL)
	{

		$this->data['admin_page_section'] = 'delete';
		$this->layout->view('admin/projects/index', $this->data);
	}

	// --------------------------------------------------------------------

	function _set_feeds($project_id)
	{
		$main_feeds = array('vcs_commits', 'developer_ticket_updates', 'api_ticket_updates', 'public_ticket_updates', 'project_notes');

		$num_feeds_updated = 0;

		foreach($main_feeds as $feed_name)
		{
			//if the record doesn't exist, create it.
			if ($record = $this->project_feeds_model->retrieve_single(array('projects_id' => $project_id, 'feed_source' => $feed_name)))
			{
				if ($record->feed_visibility != $this->input->post('feed_name'))
					$result = $this->project_feeds_model->update($record->id, array('feed_visibility' => $this->input->post($feed_name)));
				else
					$result = FALSE;

				unset($record);
			}
			else
				$result = $this->project_feeds_model->create(array('projects_id' => $project_id, 'feed_source' => $feed_name, 'feed_visibility' => $this->input->post($feed_name)));

			if ($result)
				$num_feeds_updated++;
		}

		return $num_feeds_updated;
	}

	// --------------------------------------------------------------------

	function _set_members($developers_array, $role, $project_id)
	{
		if (is_array($developers_array) && count($developers_array) > 0)
		{
			//Get a list of existing developers
			$existing_members = $this->project_members_model->retrieve(array('project_role' => $role, 'projects_id' => $project_id));
			$no_longer_members = array();

			$developers_updated = 0;

			foreach($developers_array as $curr_dev)
			{
				//Check to ensure the user actually exists
				if ( ! $this->users_model->check_record_exists($curr_dev))
					continue;

				//If the user is alrady in the project, set the record to "developer"
				if ($existing_rec = $this->project_members_model->retrieve_single(array('projects_id' => $project_id, 'users_id' => $curr_dev)))
				{
					if ($existing_rec->project_role != $role)
						$result = $this->project_members_model->update($existing_rec->id, array('project_role' => $role));
					else
						$result = FALSE;
				}
				else
					$result = $this->project_members_model->create(array('project_role' => $role, 'users_id' => $curr_dev, 'projects_id' => $project_id));

				if ($result)
					$developers_updated++;
					
				unset($result);
			}

			return $developers_updated;
		}
		else
			return 0;
	}

	// --------------------------------------------------------------------

	function _validate_create_update($is_create = TRUE)
	{
		//Create the project slug if it doesn't exist
		if ( ! $this->input->post('project_slug') OR trim($this->input->post('project_slug')) == '')
			$_POST['project_slug'] = url_title($this->input->post('project_name'), 'underscore', TRUE);

		//Validate all fields here
		$this->form_validation->set_rules('project_name', "Project Name", 'required|trim|normal_punc_space|max_length[100]');
		$this->form_validation->set_rules('project_slug', "Project Slug", 'required|trim|strtolower|alpha_dash|max_length[100]|callback__check_project_slug_unique');
		$this->form_validation->set_rules('main_url', "Main Project URL", 'trim');
		$this->form_validation->set_rules('vcs_type', "Version Control Type", 'callback__check_valid_vcs_type');
		$this->form_validation->set_rules('vcs_url', "Version Control URL", 'trim');
		$this->form_validation->set_rules('allow_devs_manage_tix', "'Allow Developers to Manage Tickets' Option", 'required');
		$this->form_validation->set_rules('allow_devs_manage_users', "'Allow Developers to Manage Users' Option", 'required');
		$this->form_validation->set_rules('allow_mgrs_manage_settings', "'Allow Managers to Manage Settings' Option", 'required');
		$this->form_validation->set_rules('allow_mgrs_manage_users', "'Allow Managers to Manage Users' Option", 'required');
		$this->form_validation->set_rules('allow_mgrs_add_notes', "'Allow Managers to Add Notes' Option", 'required');
		$this->form_validation->set_rules('allow_devs_add_notes', "'Allow Developers to Add Notes' Option", 'required');
		$this->form_validation->set_rules('vcs_commits', "Activity Feed Settings", 'callback__is_valid_activity_feed_setting');
		$this->form_validation->set_rules('developer_ticket_updates', "Activity Feed Settings", 'callback__is_valid_activity_feed_setting');
		$this->form_validation->set_rules('api_ticket_updates', "Activity Feed Settings", 'callback__is_valid_activity_feed_setting');
		$this->form_validation->set_rules('public_ticket_updates', "Activity Feed Settings", 'callback__is_valid_activity_feed_setting');
		$this->form_validation->set_rules('project_notes', "Activity Feed Settings", 'callback__is_valid_activity_feed_setting');

		$this->form_validation->set_rules('cf_1_url', "Custom Feed #1", 'trim|valid_url');
		$this->form_validation->set_rules('cf_2_url', "Custom Feed #2", 'trim|valid_url');
		$this->form_validation->set_rules('cf_3_url', "Custom Feed #3", 'trim|valid_url');

		$this->form_validation->set_rules('proj_managers', 'Project Managers', 'callback__validate_proj_managers');
		$this->form_validation->set_rules('proj_developers', 'Project Developers', 'callback__validate_proj_developers');

		if ($this->form_validation->run())
			return TRUE;
		else
			return FALSE;
	}

	// --------------------------------------------------------------------

	/*
	 * Form Callbacks
	 */

	function _validate_proj_managers($arr)
	{
		if ( ! is_array($arr))
		{
			$this->form_validation->set_message('_validate_proj_managers', "An invalid value was sent for the %s field.");
			return FALSE;
		}
		elseif (count($arr) < 1)
		{
			$this->form_validation->set_message('_validate_proj_managers', "The project must have at least one manager.");
			return FALSE;
		}
		else
			return TRUE;
	}

	// --------------------------------------------------------------------

	function _validate_proj_developers($arr)
	{
		if ( ! is_array($arr))
		{
			$this->form_validation->set_message('_validate_proj_developers', "An invalid value was sent for the %s field.");
			return FALSE;
		}
		else
			return TRUE;
	}

	// --------------------------------------------------------------------

	function _is_valid_activity_feed_setting($str)
	{
		$valid_settings = array('public', 'private', 'project_members_only', 'off');

		if ( ! in_array($str, $valid_settings))
		{
			$this->form_validation->set_message('_is_valid_activity_feed_settings', "The %s field is not a valid activity feed setting!");
			return FALSE;
		}
		else
			return TRUE;
	}

	// --------------------------------------------------------------------

	function _check_valid_vcs_type($str)
	{
		if ( ! in_array($str, $this->data['vcs_types']) && $str != 'no_repo')
		{
			$this->form_validation->set_message('_check_valid_vcs_type', "The %s field must be a valid, installed version control system type!");
			return FALSE;
		}
		else
			return TRUE;
	}

	// --------------------------------------------------------------------

	function _check_project_slug_unique($str)
	{
		if ($this->projects_model->retrieve_single(array('slug' => $str)) !== FALSE)
		{
			$this->form_validation->set_message('_check_project_slug_unique', "A project with that name already exists in the database!");
			return FALSE;
		}
		else
			echo TRUE;
	}
}

/* End of file projects.php */
/* Location: ./system/application/controllers/admin/projects.php */